import open3d as o3d
import numpy as np
import cv2
'''
cv-yolov5的环境可以跑
运行出现coredump
'''
def render_from_viewpoint(mesh_path, camera_position, look_at, up_vector=np.array([0, 1, 0]), output_path="render.png"):
    # 加载网格
    mesh = o3d.io.read_triangle_mesh(mesh_path)
    mesh.compute_vertex_normals()

    width_render = 640
    hegiht_render = 480
    # 创建一个场景
    print("### before")
    # scene = o3d.visualization.rendering.Open3DScene(o3d.visualization.rendering.OffscreenRenderer(width_render, hegiht_render).scene)
    scene = o3d.visualization.draw([mesh]) 
    print("### after")
    scene.add_geometry("mesh", mesh, o3d.visualization.rendering.MaterialRecord())

    # 设置相机内参（简化，默认焦距）
    width, height = width_render, hegiht_render
    fov = 60.0  # 视野角
    renderer = o3d.visualization.rendering.OffscreenRenderer(width, height)
    renderer.scene.add_geometry("mesh", mesh, o3d.visualization.rendering.MaterialRecord())

    center = np.asarray(look_at)
    eye = np.asarray(camera_position)
    up = np.asarray(up_vector)

    renderer.setup_camera(fov, center, eye, up)
    image = renderer.render_to_image()
    # cv2.imshow("Simulated Drive View", image)
    # 保存图像
    o3d.io.write_image(output_path, image)
    print(f"[✔] 渲染完成，保存到: {output_path}")

# 示例调用
if __name__ == "__main__":
    mesh_path = "/data/workspace/3D/room_ws/dense_291_individual/meshed-poisson.ply"
    
    # 模拟一个相机位置 + 朝向
    camera_position = np.array([0.0, 1.5, -33.0])  # 相机在场景前方
    look_at = np.array([0.0, 1.5, 0.0])           # 看向场景中心

    render_from_viewpoint(mesh_path, camera_position, look_at)
